﻿using EFCore.BulkExtensions;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace iWare.Wms.Application
{
    /// <summary>
    /// ERP模块服务
    /// </summary>
    [Route("api/ERP")]
    [ApiDescriptionSettings("ERP模块", Name = "ERP", Order = 100)]

    public class ERPService : IDynamicApiController, ITransient
    {
        private readonly ISqlRepository<ERPDbContextLocator> _ErpRep;
        private readonly IRepository<SysUser, MasterDbContextLocator> _sysUserRep; //仓库字典类型仓储
        private readonly IRepository<SysUserRole, MasterDbContextLocator> _sysUserRoleRep; //仓库字典类型仓储
        private readonly IRepository<WareDicType, MasterDbContextLocator> _wareDicTypeRep; //仓库字典类型仓储
        private readonly IRepository<WareDictData, MasterDbContextLocator> _wareDictDataRep; //仓库字典值仓储
        private readonly IRepository<SupplierInfo, MasterDbContextLocator> _supplierInfoRep; //供应商基本信息仓储
        private readonly IRepository<ProjectManage, MasterDbContextLocator> _projectManageRep; //项目管理仓储
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep; //物料仓储
        private readonly IRepository<WareMaterialWarehouse, MasterDbContextLocator> _wareMaterialWarehouseRep; //品号仓库仓储
        private readonly IRepository<PurchaseOrder, MasterDbContextLocator> _purchaseOrderRep; //采购订单仓储
        private readonly IRepository<WareOrder, MasterDbContextLocator> _wareOrderRep; //出库单据仓储
        private readonly IRepository<WareOrderDetails, MasterDbContextLocator> _wareOrderDetailsRep; //出库单据明细仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="ErpRep"></param>
        /// <param name="sysUserRep"></param>
        /// <param name="sysUserRoleRep"></param>
        /// <param name="wareDicTypeRep"></param>
        /// <param name="wareDictDataRep"></param>
        /// <param name="supplierInfoRep"></param>
        /// <param name="projectManageRep"></param>
        /// <param name="wareMaterialRep"></param>
        /// <param name="wareMaterialWarehouseRep"></param>
        /// <param name="purchaseOrderRep"></param>
        /// <param name="wareOrderRep"></param>
        /// <param name="wareOrderDetailsRep"></param>
        public ERPService(
             ISqlRepository<ERPDbContextLocator> ErpRep,
             IRepository<SysUser, MasterDbContextLocator> sysUserRep,
             IRepository<SysUserRole, MasterDbContextLocator> sysUserRoleRep,
             IRepository<WareDicType, MasterDbContextLocator> wareDicTypeRep,
             IRepository<WareDictData, MasterDbContextLocator> wareDictDataRep,
             IRepository<SupplierInfo, MasterDbContextLocator> supplierInfoRep,
             IRepository<ProjectManage, MasterDbContextLocator> projectManageRep,
             IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
             IRepository<WareMaterialWarehouse, MasterDbContextLocator> wareMaterialWarehouseRep,
             IRepository<PurchaseOrder, MasterDbContextLocator> purchaseOrderRep,
             IRepository<WareOrder, MasterDbContextLocator> wareOrderRep,
             IRepository<WareOrderDetails, MasterDbContextLocator> wareOrderDetailsRep
         )
        {
            _ErpRep = ErpRep;
            _sysUserRep = sysUserRep;
            _sysUserRoleRep = sysUserRoleRep;
            _wareDicTypeRep = wareDicTypeRep;
            _wareDictDataRep = wareDictDataRep;
            _supplierInfoRep = supplierInfoRep;
            _projectManageRep = projectManageRep;
            _wareMaterialRep = wareMaterialRep;
            _wareMaterialWarehouseRep = wareMaterialWarehouseRep;
            _purchaseOrderRep = purchaseOrderRep;
            _wareOrderRep = wareOrderRep;
            _wareOrderDetailsRep = wareOrderDetailsRep;
        }
        #endregion

        /// <summary>
        /// 采购单头-LES采购主表 数据同步使用
        /// </summary>
        [HttpGet("purchase")]
        [AllowAnonymous]
        public async Task RedPURTC()
        {
            var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");

            var purtcOutputList = await _ErpRep
                .SqlQueryAsync<PURTCOutput>
                (@"select TC001, --采购单别
	                      TC002, --采购单号
	                      TC003, --采购日期
	                      TC004, --供应商
	                      TC009, --备注
	                      TC011, --采购人员
	                      TC023, --数量合计
	                      TC047, --项目编号
	                      UDF01, --收货地址
	                      TC030, --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                          TCD01  --是否结束 N:未结束、Y:结束 [DEF:""N""]
                   from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0 and TC003>'" + whereTime + "' order by TC003 desc");

            //循环判断LES系统中是否包含该采购信息以及状态变化
            List<PurchaseOrder> PurchaseOrderList = new List<PurchaseOrder>();
            foreach (var item in purtcOutputList)
            {
                var isExists = await _purchaseOrderRep
                    .AnyAsync(u => u.PurchaseNo == item.TC002 && u.PurchaseType == item.TC001 && u.Status != PurchaseStatusEnum.Delete);
                //不存在执行新增操作
                if (!isExists)
                {
                    var addItem = new PurchaseOrder()
                    {
                        PurchaseType = item.TC001.Trim(),
                        PurchaseNo = item.TC002.Trim(),
                        PurchaseDate = DateTime.ParseExact(item.TC003.ToString().Trim(), "yyyyMMdd",
                        System.Globalization.CultureInfo.CurrentCulture),
                        SupplierInfoCode = item.TC004.Trim(),
                        Remark = item.TC009 == null ? "" : item.TC009.Trim(),
                        PurchaserUserId = item.TC011.Trim(),
                        PurchaseNumber = item.TC023,
                        ProjectCode = item.TC047.Trim(),
                        Address = item.UDF01.Trim(),
                        Status = PurchaseStatusEnum.NotProgress,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    PurchaseOrderList.Add(addItem);
                }
            }

            //批量新增 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            _purchaseOrderRep.Context.BulkInsert(PurchaseOrderList);
        }

        /// <summary>
        /// 供应商创建送货单的二次判断
        /// </summary>
        /// <returns></returns>
        [HttpPost("checkpurchase")]
        [AllowAnonymous]
        public async Task<PURTCResult> CheckPURTC(PURTCSearch PURTCSearch)
        {
            var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");

            var purtcOutputList = await _ErpRep
                .SqlQueryAsync<PURTCOutput>
                (@"select TC001, --采购单别
	                      TC002, --采购单号
	                      TC003, --采购日期
	                      TC004, --供应商
	                      TC009, --备注
	                      TC011, --采购人员
	                      TC023, --数量合计
	                      TC047, --项目编号
	                      UDF01, --收货地址
	                      TC030, --签核状态码  0.待处理、S.传送中、1.签核中、2.退件、3.已核准、4.撤销审核中、5.作废中、6.取消作废中、N.不运行电子签核
                          TCD01  --是否结束 N:未结束、Y:结束 [DEF:""N""]
                   from PURTC where TCD01 = 'N' and TC030 = '3' and TC023 > 0  and TC002='" + PURTCSearch.TC002 + "' and TC001='" + PURTCSearch.TC001 + "'");
            if (purtcOutputList.Count > 0)
            {
                return new PURTCResult
                {
                    IsCreate = true
                };
            }
            else
            {
                //修改LES系统单据的状态
                var model = await _purchaseOrderRep
                    .SingleOrDefaultAsync(u => u.PurchaseNo == PURTCSearch.TC002
                    && u.PurchaseType == PURTCSearch.TC001 && u.Status != PurchaseStatusEnum.Delete, true);
                if (model != null)
                {
                    model.Status = PurchaseStatusEnum.Delete;
                }
                return new PURTCResult
                {
                    IsCreate = false,
                    Message = "采购单被撤销或不存在!"
                };
            }
        }

        /// <summary>
        /// 采购单身-Les采购明细表N:未结束、Y:自动结束、y:指定结束
        /// </summary>
        [HttpPost("purchasedetails")]
        [AllowAnonymous]
        public async Task<List<PURTDOutput>> RedPURTD(PURTCSearch PURTCSearch)
        {
            if (string.IsNullOrEmpty(PURTCSearch.TC002)) throw Oops.Oh(ErrorCode.D1011);
            return await _ErpRep
                .SqlQueryAsync<PURTDOutput>
                (@"select TD001, --采购单别
	                      TD002, --采购单号
	                      TD003, --序号
	                      TD004, --品号
	                      TD005, --品名
	                      TD006, --规格
	                      TD008, --采购数量
	                      TD009, --单位
	                      TD014, --备注
	                      TD022, --项目编号
	                      UDF03, --参数
                          TD016, --N:未结束、Y:自动结束、y:指定结束
                          TD018  --审核码
                   from PURTD where TD018='Y' and TD002='" + PURTCSearch.TC002 + "' and TD001='" + PURTCSearch.TC001 + "'");//TD016='N' and
        }

        /// <summary>
        /// 调拨单头-LES单据主表 数据同步使用
        /// </summary>
        [HttpGet("order")]
        [AllowAnonymous]
        public async Task RedINVTA()
        {
            var invtaOutputList = await _ErpRep
                .SqlQueryAsync<INVTAOutput>
                (@"select TA033,  --项目编号
	                      TA001,  --单别(1201、1202、1203、1204（12开头)
	                      TA002,  --单号
	                      TA003,  --交易日期（[FORMATE:YMD]）
						  TA004,  --部门编号
						  TA005,  --备注
                          TA006,  --审核码（Y/N/V）
						  TA008,  --工厂编号
	                      TA009,  --单据性质码（11.一般单据、12.调拨单）
	                      TA011,  --总数量
	                      TA014,  --单据日期
	                      TA015,  --审核者
	                      UDF01,  --（工位编号）用户自定义字段1
	                      UDF02,  --（主件品号）用户自定义字段1
	                      UDF08   --（设备编号）用户自定义字段1
                   from INVTA where TA001 in ('1201','1202','1203','1204','1299','2D01','1108','2205') and TA006='Y' 
                   and TA002!='20171219001' and TA009=12 and DATEDIFF(dd,TA014,GETDATE())<=3 order by TA014 desc");//TA001 like '12%' 

            //循环判断LES系统中是否包含该调拨信息
            List<WareOrder> orderList = new List<WareOrder>();
            foreach (var invta in invtaOutputList)
            {
                var wareOrder = await _wareOrderRep.FirstOrDefaultAsync(u => u.OrderCategory == invta.TA001.Trim() && u.OrderNo == invta.TA002.Trim()
                && u.ProjectCode == invta.TA033.Trim() && u.OrderQuantityTotal == invta.TA011);

                //不存在执行新增操作
                if (wareOrder == null)
                {
                    var addOrder = new WareOrder()
                    {
                        Id = YitIdHelper.NextId(),
                        OrderNo = invta.TA002.Trim(),
                        OrderCategory = invta.TA001.Trim(),
                        OrderType = IssueTypeEnum.DIAOBO,
                        ProjectCode = invta.TA033.Trim(),
                        OrderQuantityTotal = invta.TA011,
                        DepartmentNumber = invta.TA004.Trim(),
                        OrderRemark = invta.TA005.Trim(),
                        AuditCode = invta.TA006.Trim(),
                        FactoryCode = invta.TA008.Trim(),
                        OrderDate = invta.TA014.Trim(),
                        StationNumber = invta.UDF01.Trim(),
                        MainPartNumber = invta.UDF02.Trim(),
                        EquipmentNumber = invta.UDF08.Trim(),
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };

                    // 新增单据主表信息
                    await _wareOrderRep.InsertNowAsync(addOrder);

                    // 批量新增单据明细信息
                    var orderDetailsList = await RedINVTB(addOrder);
                    await _wareOrderDetailsRep.Context.BulkInsertAsync(orderDetailsList);
                }
                else
                {
                    // 批量新增单据明细信息
                    var orderDetailsList = await RedINVTB(wareOrder);
                    await _wareOrderDetailsRep.Context.BulkInsertAsync(orderDetailsList);
                }
            }
        }

        /// <summary>
        /// 调拨单身-Les单据明细表
        /// </summary>
        [HttpPost("orderdetails")]
        [AllowAnonymous]
        [NonAction]
        public async Task<List<WareOrderDetails>> RedINVTB(WareOrder order)
        {
            if (string.IsNullOrEmpty(order.OrderNo)) throw Oops.Oh(ErrorCode.D1011);
            var invtbOutputList = await _ErpRep
                .SqlQueryAsync<INVTBOutput>
                (@"select  TB012,   --转出库
		                   TB013,   --转入库
		                   TB021,   --项目编号
		                   TB029,   --转出库位
		                   TB030,   --转入库位
		                   TB001,   --单别
		                   TB002,   --单号
		                   TB003,   --序号
		                   TB004,   --品号
		                   TB005,   --品名
		                   TB006,   --规格
		                   TB007,   --数量
		                   TB008,   --单位
		                   TB009,   --库存数量
						   TB018,   --审核码
						   CREATOR, --审核者
                           TB017,   --备注
                           UDF02    --参数
                   from INVTB where TB018='Y' and TB001='" + order.OrderCategory + "' and  TB002='" + order.OrderNo + "' and TB021='" + order.ProjectCode + "' order by CREATE_DATE desc");

            //循环判断LES系统中是否包含该调拨明细信息
            List<WareOrderDetails> orderDetailsList = new List<WareOrderDetails>();
            foreach (var invtb in invtbOutputList)
            {
                var isExists = await _wareOrderDetailsRep.AnyAsync(u => u.WareOrder.OrderCategory == invtb.TB001.Trim() && u.WareOrder.OrderNo == invtb.TB002.Trim()
                && u.ProjectCode == invtb.TB021.Trim() && u.Code == invtb.TB004.Trim() && u.SpecificationModel == invtb.TB006.Trim());

                //不存在执行新增操作
                if (!isExists)
                {
                    //获取物料的检验方式
                    var InspectionMethod = InspectionMethodEnum.mianjian;
                    var wareMateriaModel = await _wareMaterialRep.FirstOrDefaultAsync(n => n.Code == invtb.TB004.Trim()
                    && n.Name == invtb.TB005.Trim() && n.SpecificationModel == invtb.TB006.Trim());
                    if (wareMateriaModel != null) InspectionMethod = wareMateriaModel.InspectionMethod;

                    // 品牌名称查询
                    var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == invtb.TB004.Trim()
                    && z.Name == invtb.TB005.Trim() && z.SpecificationModel == invtb.TB006.Trim());

                    var addOrderDetails = new WareOrderDetails()
                    {
                        Id = YitIdHelper.NextId(),
                        OrderId = order.Id,
                        ProjectCode = invtb.TB021.Trim(),
                        XuHao = invtb.TB003.Trim(),
                        Code = invtb.TB004.Trim(),
                        Name = invtb.TB005.Trim(),
                        SpecificationModel = invtb.TB006.Trim(),
                        Unit = invtb.TB008.Trim(),
                        BrandName = wareMaterial == null || wareMaterial.BrandName == "无" ? "" : wareMaterial.BrandName,
                        InspectionMethod = InspectionMethod,
                        OrderQuantity = invtb.TB007,
                        ActualQuantity = new decimal(0.00),
                        SingleCategory = invtb.TB001.Trim(), //单别
                        TransferToIssue = invtb.TB012.Trim(), //转出库
                        TransferToReceipt = invtb.TB013.Trim(), //转入库
                        TransferOutLocation = invtb.TB029.Trim(), //转出库位
                        TransferredILocation = invtb.TB030.Trim(), //转入库位
                        OrderParameter = invtb.UDF02.Trim(), //参数
                        OrderRemark = invtb.TB017.Trim(), //备注
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    orderDetailsList.Add(addOrderDetails);
                }
            }

            return orderDetailsList;
        }

        /// <summary>
        /// 迁移物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addMaterial")]
        [AllowAnonymous]
        public async Task AddMaterial()
        {
            var materialList = await _ErpRep
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB");

            List<WareMaterial> addMaterialList = new List<WareMaterial>();

            foreach (var item in materialList)
            {
                var isExists = await _wareMaterialRep
                    .AnyAsync(u => u.Code.Equals(item.MB001) && u.Name.Equals(item.MB002));

                //不存在执行新增操作
                if (!isExists)
                {
                    //抽检方式
                    var inspectionMethod = InspectionMethodEnum.mianjian;
                    if (item.MB043.Equals(0))
                        inspectionMethod = InspectionMethodEnum.mianjian;
                    else if (item.MB043.Equals(1))
                        inspectionMethod = InspectionMethodEnum.choujian_jianliang;
                    else if (item.MB043.Equals(2))
                        inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
                    else if (item.MB043.Equals(3))
                        inspectionMethod = InspectionMethodEnum.choujian_jiayan;
                    else
                        inspectionMethod = InspectionMethodEnum.quanjian;

                    var addMaterialModel = new WareMaterial
                    {
                        Code = item.MB001 == null ? "" : item.MB001.Trim(),
                        Name = item.MB002 == null ? "" : item.MB002.Trim(),
                        SpecificationModel = item.MB003 == null ? "" : item.MB003.Trim(),
                        Unit = item.MB004 == null ? "" : item.MB004.Trim(),
                        Describe = item.MB009 == null ? "" : item.MB009.Trim(),
                        InspectionMethod = inspectionMethod,
                        Quantity = item.MB064,
                        BrandName = item.UDF07,
                        SupplerCode = "",
                        IsJiaJi = YesOrNot.N,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addMaterialList.Add(addMaterialModel);
                }
            }
            // 批量新增
            await _wareMaterialRep.Context.BulkInsertAsync(addMaterialList);
        }

        /// <summary>
        /// 根据条件查询物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("selectMaterial")]
        [AllowAnonymous]
        public async Task<WareMaterial> SelectMaterial(string code, string specificationModel)
        {
            var materialList = await _ErpRep
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB where MB001='" + code + "' and MB003='" + specificationModel + "'");

            var materialErpInputModel = materialList.FirstOrDefault();

            //抽检方式
            var inspectionMethod = InspectionMethodEnum.mianjian;
            if (materialErpInputModel.MB043.Equals(0))
                inspectionMethod = InspectionMethodEnum.mianjian;
            else if (materialErpInputModel.MB043.Equals(1))
                inspectionMethod = InspectionMethodEnum.choujian_jianliang;
            else if (materialErpInputModel.MB043.Equals(2))
                inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
            else if (materialErpInputModel.MB043.Equals(3))
                inspectionMethod = InspectionMethodEnum.choujian_jiayan;
            else
                inspectionMethod = InspectionMethodEnum.quanjian;

            return new WareMaterial
            {
                Code = materialErpInputModel.MB001 == null ? "" : materialErpInputModel.MB001.Trim(),
                Name = materialErpInputModel.MB002 == null ? "" : materialErpInputModel.MB002.Trim(),
                SpecificationModel = materialErpInputModel.MB003 == null ? "" : materialErpInputModel.MB003.Trim(),
                Unit = materialErpInputModel.MB004 == null ? "" : materialErpInputModel.MB004.Trim(),
                Describe = materialErpInputModel.MB009 == null ? "" : materialErpInputModel.MB009.Trim(),
                InspectionMethod = inspectionMethod,
                Quantity = materialErpInputModel.MB064,
                BrandName = materialErpInputModel.UDF07,
                SupplerCode = "",
                IsJiaJi = YesOrNot.N,
                CreatedUserName = "LES SYSTEM",
                CreatedTime = DateTimeOffset.Now
            };
        }

        /// <summary>
        /// 迁移品号仓库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addMaterialWarehouse")]
        [AllowAnonymous]
        public async Task AddMaterialWarehouse()
        {
            var materialWarehouseList = await _ErpRep
                .SqlQueryAsync<MaterialWarehouseErpInput>
                (@"select MC001, --品号
	                      MC002, --仓库
	                      MC004, --安全存量
	                      MC006, --经济批量
	                      MC007  --库存数量
                   from INVMC");

            var addMaterialWarehouseList = new List<WareMaterialWarehouse>();

            foreach (var item in materialWarehouseList)
            {
                var isExists = await _wareMaterialWarehouseRep
                    .AnyAsync(u => u.Code.Equals(item.MC001) && u.Name.Equals(item.MC002));

                //不存在执行新增操作
                if (!isExists)
                {
                    var addMaterialWarehouseModel = new WareMaterialWarehouse
                    {
                        Code = item.MC001 == null ? "" : item.MC001.Trim(),
                        Name = item.MC002 == null ? "" : item.MC002.Trim(),
                        SafetyQuantity = item.MC004,
                        EconomicQuantity = item.MC006,
                        InventoryQuantity = item.MC007,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addMaterialWarehouseList.Add(addMaterialWarehouseModel);
                }
            }

            // 批量新增
            await _wareMaterialWarehouseRep.Context.BulkInsertAsync(addMaterialWarehouseList);
        }

        /// <summary>
        /// 获取供应商信息按钮
        /// </summary>
        /// <returns></returns>
        [HttpPost("addSupplierInfo")]
        [AllowAnonymous]
        public async Task AddSupplierInfo()
        {
            var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");
            //查询近一个月的供应商信息
            var supplierInfoList = await _ErpRep
                .SqlQueryAsync<SupplierInfoErpInput>
                (@"select MA001, --供应商编号
	                      MA002, --简称
	                      MA003, --公司全称
	                      MA008, --TEL(一)
	                      MA012, --负责人
	                      MA013, --联系人（一）
	                      MA014, --联系地址（一）
                          MA022  --创建时间
                   from PURMA where MA022>'" + whereTime + "' order by MA022 desc");

            var addSupplierInfoList = new List<SupplierInfo>();

            foreach (var item in supplierInfoList)
            {
                var isExists = await _supplierInfoRep.AnyAsync(u => u.Code.Equals(item.MA001));

                string code = item.MA001 == null ? "" : item.MA001.Trim(); //账号
                //不存在执行新增操作
                if (!isExists)
                {
                    var addSupplierInfoModel = new SupplierInfo
                    {
                        Code = item.MA001 == null ? "" : item.MA001.Trim(),
                        AbbreviationName = item.MA002 == null ? "" : item.MA002.Trim(),
                        Name = item.MA003 == null ? "" : item.MA003.Trim(),
                        Tel = item.MA008 == null ? "" : item.MA008.Trim(),
                        LeadingCadre = item.MA012 == null ? "" : item.MA012.Trim(),
                        Contacts = item.MA013 == null ? "" : item.MA013.Trim(),
                        ContactAddress = item.MA014 == null ? "" : item.MA014.Trim(),
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addSupplierInfoList.Add(addSupplierInfoModel);
                }
                else
                {
                    var supplierInfoMode = await _supplierInfoRep.FirstOrDefaultAsync(u => u.Code.Equals(item.MA001));
                    supplierInfoMode.AbbreviationName = item.MA002 == null ? "" : item.MA002.Trim();
                    supplierInfoMode.Name = item.MA003 == null ? "" : item.MA003.Trim();
                    supplierInfoMode.Tel = item.MA008 == null ? "" : item.MA008.Trim();
                    supplierInfoMode.LeadingCadre = item.MA012 == null ? "" : item.MA012.Trim();
                    supplierInfoMode.Contacts = item.MA013 == null ? "" : item.MA013.Trim();
                    supplierInfoMode.ContactAddress = item.MA014 == null ? "" : item.MA014.Trim();

                    await _supplierInfoRep.UpdateAsync(supplierInfoMode);
                }

                var isExist = await _sysUserRep.AnyAsync(u => u.Account == code && !u.IsDeleted, false, true);
                if (!isExist)
                {
                    // 新增用户表信息
                    var user = new SysUser
                    {
                        Id = YitIdHelper.NextId(),
                        Account = item.MA001 == null ? "" : item.MA001.Trim(),
                        NickName = item.MA001 == null ? "" : item.MA001.Trim(),
                        Password = "e10adc3949ba59abbe56e057f20f883e",
                        Name = item.MA003 == null ? "" : item.MA003.Trim(),
                        AdminType = AdminType.Supplier,
                    };
                    await _sysUserRep.InsertNowAsync(user, true);

                    // 新增用户角色表信息
                    var sysUserRole = new SysUserRole
                    {
                        SysUserId = user.Id,
                        SysRoleId = 396085390729285
                    };
                    await _sysUserRoleRep.InsertNowAsync(sysUserRole);
                }
                else
                {
                    var sysUserMode = await _sysUserRep.FirstOrDefaultAsync(u => u.Account == code);
                    sysUserMode.Name = item.MA003 == null ? "" : item.MA003.Trim();
                    await _sysUserRep.UpdateAsync(sysUserMode);
                }
            }

            // 批量新增
            await _supplierInfoRep.Context.BulkInsertAsync(addSupplierInfoList);
        }

        /// <summary>
        /// 迁移供应商基本信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddSupplierInfoAll")]
        [AllowAnonymous]
        public async Task AddSupplierInfoAll()
        {
            var supplierInfoList = await _ErpRep
                .SqlQueryAsync<SupplierInfoErpInput>
                (@"select MA001, --供应商编号
	                      MA002, --简称
	                      MA003, --公司全称
	                      MA008, --TEL(一)
	                      MA012, --负责人
	                      MA013, --联系人（一）
	                      MA014, --联系地址（一）
                          MA022  --创建时间
                   from PURMA order by MA022 desc");

            var addSupplierInfoList = new List<SupplierInfo>();

            foreach (var item in supplierInfoList)
            {
                var isExists = await _supplierInfoRep.AnyAsync(u => u.Code.Equals(item.MA001));

                string code = item.MA001 == null ? "" : item.MA001.Trim(); //账号
                //不存在执行新增操作
                if (!isExists)
                {
                    var addSupplierInfoModel = new SupplierInfo
                    {
                        Code = item.MA001 == null ? "" : item.MA001.Trim(),
                        AbbreviationName = item.MA002 == null ? "" : item.MA002.Trim(),
                        Name = item.MA003 == null ? "" : item.MA003.Trim(),
                        Tel = item.MA008 == null ? "" : item.MA008.Trim(),
                        LeadingCadre = item.MA012 == null ? "" : item.MA012.Trim(),
                        Contacts = item.MA013 == null ? "" : item.MA013.Trim(),
                        ContactAddress = item.MA014 == null ? "" : item.MA014.Trim(),
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addSupplierInfoList.Add(addSupplierInfoModel);
                }
            }

            // 批量新增
            await _supplierInfoRep.Context.BulkInsertAsync(addSupplierInfoList);
        }

        /// <summary>
        /// 迁移项目编号信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addProject")]
        [AllowAnonymous]
        public async Task AddProject()
        {
            var projectManageList = await _ErpRep
                .SqlQueryAsync<ProjectManageErpInput>
                (@"select NO001, --项目编号
	                      NO002, --项目名称
	                      NO003  --项目说明
                   from CMSNO where CREATE_DATE >'20180000000000000'");

            var addProjectManageList = new List<ProjectManage>();

            foreach (var item in projectManageList)
            {
                var isExists = await _projectManageRep
                    .AnyAsync(u => u.Code.Equals(item.NO001) && u.Name.Equals(item.NO002));

                //不存在执行新增操作
                if (!isExists)
                {
                    var addProjectManageModel = new ProjectManage
                    {
                        Code = item.NO001 == null ? "" : item.NO001.Trim(),
                        Name = item.NO002 == null ? "" : item.NO002.Trim(),
                        Describe = item.NO003 == null ? "" : item.NO003.Trim(),
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addProjectManageList.Add(addProjectManageModel);
                }
            }

            // 批量新增
            await _projectManageRep.Context.BulkInsertAsync(addProjectManageList);
        }

        /// <summary>
        /// 迁移采购人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addPurchasePersonnel")]
        [AllowAnonymous]
        public async Task AddPurchasePersonnel()
        {
            var purchasePersonnelList = await _ErpRep
                .SqlQueryAsync<PurchasePersonnelErpInput>
                (@"select MV001, --员工编号
	                      MV002 --姓名
                   from CMSMV where MV004=10 and UDF01 = 'Y'");

            var addWareDictDataList = new List<WareDictData>();

            var wareDicTypeModel = await _wareDicTypeRep.DetachedEntities
                .Where(z => z.Code.Equals("purchase_personnel") || z.Name.Equals("采购人员"))
                .ProjectToType<WareDicType>()
                .FirstOrDefaultAsync();

            var sort = 0; //定义排序
            foreach (var item in purchasePersonnelList)
            {
                var isExists = await _wareDictDataRep
                    .AnyAsync(u => u.TypeId == wareDicTypeModel.Id
                     && u.Code.Equals(item.MV001) && u.Value.Equals(item.MV002));

                //不存在执行新增操作
                if (!isExists)
                {
                    var addWareDictDataModel = new WareDictData()
                    {
                        TypeId = wareDicTypeModel != null ? wareDicTypeModel.Id : YitIdHelper.NextId(),
                        Code = item.MV001 == null || item.MV001.Trim() == "" ? "" : item.MV001.Trim(),
                        Value = item.MV002 == null || item.MV002.Trim() == "" ? item.MV001.Trim() : item.MV002.Trim(),
                        Sort = sort + 1,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    sort++;

                    addWareDictDataList.Add(addWareDictDataModel);
                }
            }

            // 批量新增字典数据
            await _wareDictDataRep.Context.BulkInsertAsync(addWareDictDataList);
        }

        /// <summary>
        /// 迁移单据类型信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addOrderType")]
        [AllowAnonymous]
        public async Task AddOrderType()
        {
            var orderTypelList = await _ErpRep
                .SqlQueryAsync<OrderTypeErpInput>
                (@"select MQ001,  --单别
                          MQ002   --单据名称
                   from CMSMQ");

            var addWareDictDataList = new List<WareDictData>();

            var wareDicTypeModel = await _wareDicTypeRep.DetachedEntities
                .Where(z => z.Code.Equals("order_type") || z.Name.Equals("单据类型"))
                .ProjectToType<WareDicType>()
                .FirstOrDefaultAsync();

            var sort = 0; //定义排序
            foreach (var item in orderTypelList)
            {
                var isExists = await _wareDictDataRep
                    .AnyAsync(u => u.TypeId == wareDicTypeModel.Id
                     && u.Code.Equals(item.MQ001) && u.Value.Equals(item.MQ002));

                //不存在执行新增操作
                if (!isExists)
                {
                    var addWareDictDataModel = new WareDictData()
                    {
                        TypeId = wareDicTypeModel != null ? wareDicTypeModel.Id : YitIdHelper.NextId(),
                        Code = item.MQ001 == null || item.MQ001.Trim() == "" ? "" : item.MQ001.Trim(),
                        Value = item.MQ002 == null || item.MQ002.Trim() == "" ? item.MQ001.Trim() : item.MQ002.Trim(),
                        Sort = sort + 1,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    sort++;

                    addWareDictDataList.Add(addWareDictDataModel);
                }
            }

            // 批量新增字典数据
            await _wareDictDataRep.Context.BulkInsertAsync(addWareDictDataList);
        }


        /// <summary>
        /// 同步物料信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addMaterial1")]
        [AllowAnonymous]
        public async Task AddMaterial1()
        {
            var whereTime = DateTime.Now.ToString("yyyyMM");
            var whereTime1 = DateTime.Now.AddMonths(-1).ToString("yyyyMM");

            var materialList = await _ErpRep
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB where CREATE_DATE like '" + whereTime + "%' or CREATE_DATE like '" + whereTime1 + "%' ");

            List<WareMaterial> addMaterialList = new List<WareMaterial>();

            foreach (var item in materialList)
            {
                var isExists = await _wareMaterialRep
                    .AnyAsync(u => u.Code.Equals(item.MB001) && u.Name.Equals(item.MB002));

                //不存在执行新增操作
                if (!isExists)
                {
                    //抽检方式
                    var inspectionMethod = InspectionMethodEnum.mianjian;
                    if (item.MB043.Equals(0))
                        inspectionMethod = InspectionMethodEnum.mianjian;
                    else if (item.MB043.Equals(1))
                        inspectionMethod = InspectionMethodEnum.choujian_jianliang;
                    else if (item.MB043.Equals(2))
                        inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
                    else if (item.MB043.Equals(3))
                        inspectionMethod = InspectionMethodEnum.choujian_jiayan;
                    else
                        inspectionMethod = InspectionMethodEnum.quanjian;

                    var addMaterialModel = new WareMaterial
                    {
                        Code = item.MB001 == null ? "" : item.MB001.Trim(),
                        Name = item.MB002 == null ? "" : item.MB002.Trim(),
                        SpecificationModel = item.MB003 == null ? "" : item.MB003.Trim(),
                        Unit = item.MB004 == null ? "" : item.MB004.Trim(),
                        Describe = item.MB009 == null ? "" : item.MB009.Trim(),
                        InspectionMethod = inspectionMethod,
                        Quantity = item.MB064,
                        BrandName = item.UDF07,
                        SupplerCode = "",
                        IsJiaJi = YesOrNot.N,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addMaterialList.Add(addMaterialModel);
                }
            }
            // 批量新增
            await _wareMaterialRep.Context.BulkInsertAsync(addMaterialList);
        }
        /// <summary>
        /// 同步品号仓库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("addMaterialWarehouse1")]
        [AllowAnonymous]
        public async Task AddMaterialWarehouse1()
        {
            var whereTime = DateTime.Now.ToString("yyyyMM");
            var whereTime1 = DateTime.Now.AddMonths(-1).ToString("yyyyMM");

            var materialWarehouseList = await _ErpRep
                .SqlQueryAsync<MaterialWarehouseErpInput>
                (@"select MC001, --品号
	                      MC002, --仓库
	                      MC004, --安全存量
	                      MC006, --经济批量
	                      MC007  --库存数量
                   from INVMC where CREATE_DATE like '" + whereTime + "%' or CREATE_DATE like '" + whereTime1 + "%' ");

            var addMaterialWarehouseList = new List<WareMaterialWarehouse>();

            foreach (var item in materialWarehouseList)
            {
                var isExists = await _wareMaterialWarehouseRep
                    .AnyAsync(u => u.Code.Equals(item.MC001) && u.Name.Equals(item.MC002));

                //不存在执行新增操作
                if (!isExists)
                {
                    var addMaterialWarehouseModel = new WareMaterialWarehouse
                    {
                        Code = item.MC001 == null ? "" : item.MC001.Trim(),
                        Name = item.MC002 == null ? "" : item.MC002.Trim(),
                        SafetyQuantity = item.MC004,
                        EconomicQuantity = item.MC006,
                        InventoryQuantity = item.MC007,
                        CreatedUserName = "LES SYSTEM",
                        CreatedTime = DateTimeOffset.Now
                    };
                    addMaterialWarehouseList.Add(addMaterialWarehouseModel);
                }
            }

            // 批量新增
            await _wareMaterialWarehouseRep.Context.BulkInsertAsync(addMaterialWarehouseList);
        }
    }
}
